package com.mindskip.xzs.security;

import com.mindskip.xzs.domain.enums.RoleEnum;
import com.mindskip.xzs.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class RestDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;

    public RestDetailsServiceImpl(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.mindskip.xzs.domain.entity.User user = userService.getUserByUserName(username);


        if (user == null) {
            throw new UsernameNotFoundException("用户名或者密码错误");
        }

        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        // 将用户的角色名加上"ROLE_"前缀并添加到grantedAuthorities中
        grantedAuthorities.add(new SimpleGrantedAuthority(RoleEnum.fromCode(user.getRole()).getRoleName()));

        return new User(user.getUserName(), user.getPassword(), grantedAuthorities);
    }
}
